<template>
  <div class="device-status-chart">
    <div v-loading="loading" class="chart-container">
      <div ref="chartRef" class="chart"></div>
    </div>
    
    <!-- 状态统计 -->
    <div class="status-summary">
      <div class="summary-item online">
        <div class="summary-value">{{ getStatusCount('online') }}</div>
        <div class="summary-label">在线设备</div>
      </div>
      <div class="summary-item offline">
        <div class="summary-value">{{ getStatusCount('offline') }}</div>
        <div class="summary-label">离线设备</div>
      </div>
      <div class="summary-item maintenance">
        <div class="summary-value">{{ getStatusCount('maintenance') }}</div>
        <div class="summary-label">维护中</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import * as echarts from 'echarts'

interface DeviceStatusData {
  status: string
  count: number
}

interface Props {
  data: DeviceStatusData[] | { online: number; offline: number; maintenance: number; total: number }
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 计算属性：标准化数据格式
const normalizedData = computed(() => {
  if (!props.data) return []
  
  // 如果是对象格式，转换为数组格式
  if (!Array.isArray(props.data)) {
    return [
      { status: 'online', count: props.data.online || 0 },
      { status: 'offline', count: props.data.offline || 0 },
      { status: 'maintenance', count: props.data.maintenance || 0 }
    ]
  }
  
  return props.data
})

const getStatusCount = (status: string) => {
  const item = normalizedData.value.find(d => d.status === status)
  return item ? item.count : 0
}

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chartInstance || !normalizedData.value?.length) return
  
  const statusColors = {
    online: '#67C23A',
    offline: '#F56C6C',
    maintenance: '#E6A23C'
  }
  
  const statusNames = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中'
  }
  
  const chartData = normalizedData.value.map(item => ({
    name: statusNames[item.status] || item.status,
    value: item.count,
    itemStyle: {
      color: statusColors[item.status] || '#909399'
    }
  }))
  
  const total = chartData.reduce((sum, item) => sum + item.value, 0)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const percent = total > 0 ? ((params.value / total) * 100).toFixed(1) : '0.0'
        return `
          <div style="margin-bottom: 5px; font-weight: bold;">${params.name}</div>
          <div>数量: <strong>${params.value}</strong></div>
          <div>占比: <strong>${percent}%</strong></div>
        `
      }
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      itemGap: 20,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: (params: any) => {
            const percent = total > 0 ? ((params.value / total) * 100).toFixed(1) : '0.0'
            return `${params.name}\n${params.value} (${percent}%)`
          },
          fontSize: 11
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 5
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            fontSize: 12,
            fontWeight: 'bold'
          }
        },
        data: chartData
      }
    ],
    animation: true,
    animationType: 'scale',
    animationEasing: 'elasticOut',
    animationDelay: function (idx: number) { return idx * 100; }
  } as any
  
  chartInstance.setOption(option, true)
}

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听数据变化
watch(() => props.data, () => {
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

// 监听加载状态
watch(() => props.loading, (loading) => {
  if (!loading) {
    nextTick(() => {
      updateChart()
    })
  }
})

onMounted(() => {
  nextTick(() => {
    initChart()
  })
  
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped lang="scss">
.device-status-chart {
  .chart-container {
    position: relative;
    
    .chart {
      width: 100%;
      height: 250px;
    }
  }
  
  .status-summary {
    display: flex;
    justify-content: space-around;
    margin-top: 15px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 6px;
    
    .summary-item {
      text-align: center;
      
      .summary-value {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 4px;
      }
      
      .summary-label {
        font-size: 12px;
        color: #909399;
      }
      
      &.online .summary-value {
        color: #67C23A;
      }
      
      &.offline .summary-value {
        color: #F56C6C;
      }
      
      &.maintenance .summary-value {
        color: #E6A23C;
      }
    }
  }
}
</style>